package com.ygqh.baby.service.impl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.service.FreemarkerService;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * Created by Zhangsai on 2017/1/4 0004.
 */
@Service
public class FreemarkerServiceImpl implements FreemarkerService {
	@Value("${templatePath}")
	private String templatePath;
	@Value("${image.upload.temp.url}")
	private String tempUrl;

	public String crateHTML(String templateFile, String htmldire, String templateHtmlFile, Map<String, Object> data) throws IOException {
		Configuration freemarkerCfg = new Configuration();
		// 加载模版文件的路径
		freemarkerCfg.setDirectoryForTemplateLoading(new File(templatePath));
		freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");
		freemarkerCfg.setLocale(Locale.CHINESE);
		try {
			// 指定模版路径
			Template template = freemarkerCfg.getTemplate(templateFile, "UTF-8");
			template.setEncoding("UTF-8");
			// 静态页面路径
			String targetPath = tempUrl;
			if (StringUtil.isNotBlank(htmldire)) {
				targetPath = tempUrl + "//" + htmldire;
				File fileDire = new File(targetPath);
				if (!fileDire.exists() && !fileDire.isDirectory()) {
					fileDire.mkdirs();
				}
			}
			File htmlFile = new File(targetPath + "//" + templateHtmlFile);
			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));
			// 处理模版并开始输出静态页面
			template.process(data, out);
			out.flush();
			out.close();
			return "";
		} catch (Exception e) {

			e.printStackTrace();
			return e.getMessage();
		}
	}

	@Override
	public String crateHTML(String templateFile, String targetHtmlFile, Map<String, Object> data) throws IOException {
		return this.crateHTML(templateFile, "", targetHtmlFile, data);
	}
}
